package com.juqimiao.outposts.spring.oauth2.api.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户信息服务类。
 * @author collin
 * @date 2019/05/02
 */
@Service("OAuthUserDetailsServiceImpl")
public class OAuthUserDetailsServiceImpl implements UserDetailsManager, UserDetailsService {

    private List<User> userDetailsList;

    private UserCache userCache = new NullUserCache();
    private PasswordEncoder passwordEncoder;

    /**
     * 实例化一个BCryptPasswordEncoder.
     * @return BCryptPasswordEncoder {@link BCryptPasswordEncoder}.
     */
    @Bean
    public PasswordEncoder getPasswordEncoder() {
        passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder;
    }

    public OAuthUserDetailsServiceImpl(){
        getPasswordEncoder();
        inital();

    }
    /**
     * 通过指定id获取用户信息.
     *
     * @param s 用户标识.
     * @return 用户信息对象 {@link UserDetails}.
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s)
            throws UsernameNotFoundException {

        try {
            if (s != null) {
                User user = this.userDetailsList
                        .stream()
                        .filter(u -> u.getUsername().equals(s))
                        .findFirst()
                        .get();

                return User.withUsername(user.getUsername())
                        .password(user.getPassword())
                        .accountExpired(!user.isAccountNonExpired())
                        .accountLocked(!user.isAccountNonLocked())
                        .credentialsExpired(!user.isCredentialsNonExpired())
                        .disabled(!user.isEnabled())
                        //.passwordEncoder(password -> passwordEncoder.encode(password))
                        .authorities(user.getAuthorities())
                        .build();

            }
            return null;
        } catch (Exception e) {
            throw new UsernameNotFoundException(s + ", Not found");
        }
    }

    private void inital() {


        userDetailsList = new ArrayList<>();
        List<GrantedAuthority> authorities = new ArrayList<>();
//        GrantedAuthority authority1 = new SimpleGrantedAuthority("ROLE_USER:EMPLOYEE:ADDNEW");
//        authorities.add(authority1);
        GrantedAuthority authority2 = new SimpleGrantedAuthority("ROLE_USER:EMPLOYEE:MODIFY");
        authorities.add(authority2);
        User user1 = new User("demoUser1",
                passwordEncoder.encode("123456"),
                true,
                true,
                true,
                true,
                authorities);
        userDetailsList.add(user1);
    }

    @Override
    public void createUser(UserDetails userDetails) {

    }

    @Override
    public void updateUser(UserDetails userDetails) {
        userCache.putUserInCache(userDetails);
    }

    @Override
    public void deleteUser(String s) {
        userCache.removeUserFromCache(s);
    }

    @Override
    public void changePassword(String s, String s1) {

        userCache.putUserInCache(loadUserByUsername(s));
    }

    @Override
    public boolean userExists(String s) {
        return loadUserByUsername(s) != null;
    }
}
